package main

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/imroc/req/v3"
	"github.com/tidwall/gjson"
)

// RDLDevice RDL设备配置
type RDLDevice struct {
	Host       string `toml:"host,omitempty"`
	Port       int    `toml:"port,omitempty"`
	Username   string `toml:"username,omitempty"`
	Password   string `toml:"password,omitempty"`
	HTTPScheme string `toml:"http_scheme,omitempty"`

	client *req.Client
}

// newHttpClient 返回HTTP客户端实例
func (d *RDLDevice) newHttpClient() *req.Client {
	if d.client == nil {
		if d.Host == "" {
			panic("host must not be empty")
		}
		d.HTTPScheme = strings.ToLower(d.HTTPScheme)

		port := uint16(80)
		if d.HTTPScheme == "https" {
			port = 443
		}
		if d.Port != 0 {
			port = uint16(d.Port)
		}

		d.client = req.C().
			SetCommonBasicAuth(d.Username, d.Password).
			EnableInsecureSkipVerify().
			SetBaseURL(fmt.Sprintf("%s://%s:%d/goform", d.HTTPScheme, d.Host, port)).
			SetTimeout(10 * time.Second).
			SetCommonRetryCount(2).
			DisableAutoDecode(). // 禁用自动解码，优化性能
			EnableForceHTTP1()   // 强制使用http1.1
	}

	return d.client
}

// FetchJSON 返回 gjson.Result
func (d *RDLDevice) FetchJSON(ctx context.Context, pth string) (*gjson.Result, time.Duration, error) {
	st := time.Now()
	req, err := d.newHttpClient().R().SetContext(ctx).Get(pth)
	if err != nil {
		return nil, -1, err
	}
	result := gjson.Parse(req.String())
	return &result, time.Since(st), nil
}

// PrometheusLabelValues 返回 Prometheus label values
func (d *RDLDevice) PrometheusLabelValues() []string {
	return []string{d.Host}
}
